# Copyright (c) vertbyqb 2021
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>

# Dependencies:
#    - pandoc
#       - https://github.com/jgm/pandoc
#       - License: GPL version 2 or later, see COPYRIGHT file

from flbry.variables import *
from subprocess import *
import json
import os

def pandoc_convert(command, args):
    """Converts a file on the LBRY network using pandoc"""

    original_args = args

    try:
        x = check_output(["pandoc", "--help"])
    except FileNotFoundError:
        center("Pandoc is not installed", "bdrd")
        center("Install pandoc and try again", "bdrd")
        return original_args

    # The media types pandoc can convert from
    # I don't know a smart way to convert media types to inputs pandoc knows, so I'm manually writing a dictionary
    # This is by no means comprehensive, feel free to send a pull request with more at the repository: https://notabug.org/vertbyqb/FastLBRY-Plugins
    # See `pandoc --list-input-formats`
    from_types = {
            "text/markdown": "markdown",
            "application/x-tex": "latex",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
            "application/epub+zip": "epub",
            "text/html": "html",
            "application/json": "json",
            "application/vnd.oasis.opendocument.text": "odt",
            "text/x-rst": "rst",
            "text/csv": "csv"
    }

    # Get a list of output types from pandoc itself
    to_types = check_output(["pandoc", "--list-output-formats"])
    to_types = to_types.decode("utf-8").split("\n")

    media_type = args["value"]["source"]["media_type"]

    try:
        from_type = from_types[media_type]
    except KeyError:
        center("Can't convert from '"+media_type+"'!", "bdrd")
        return original_args

    # Get the path of the downloaded file
    path = check_output(["flbry/lbrynet", "get", args["canonical_url"]])
    path = json.loads(path)
    path = path["download_path"]

    command = command.split()

    # The user could type "pandoc <type> <out_file>"
    # Or they could just type "pandoc"
    try:
        to_type = command[1]
    except:
        complete(to_types)
        to_type = input(typing_dots("Type to convert to.", to_text=True))

    if not to_type in to_types:
        center("Can't convert to '"+to_type+"'!", "bdrd")
        return original_args

    try:
        out_file = command[2]
    except:
        out_file = input(typing_dots("Output file (press enter for default).", to_text=True))

    if not out_file:
        # Get the filename and strip the extension from it, then add an extension of the to_type
        # So:      /home/user/Documents/example.md
        # becomes: /home/user/Documents/example.pdf

        out_path = os.path.split(path)
        filename = out_path[-1]
        out_path = out_path[0]
        filename = os.path.splitext(filename)[0]

        # This leads to some wacky things like ".markdown" or ".latex"
        # But I don't want to maintain a dictionary and it's only for identification of the file (Unix-like OSs don't care about file extensions)
        # If you want to fix this, submit a pull request to the git repository: https://notabug.org/vertbyqb/FastLBRY-Plugins
        filename = filename + "." + to_type
        out_file = out_path + "/" + filename

    out_file = os.path.expanduser(out_file)

    center("Converting "+from_type+" to "+to_type)

    command = ["pandoc", path, "-f", from_type, "-t", to_type, "-o", out_file]
    try:
        x = check_output(command)
    except:
        center("Unable to convert file", "bdrd")
        return original_args

    center("Saved to "+out_file, "bdgr")

    return original_args

def inject_help(args):
    """Injects plugin help into applicable files"""
    # SPDX-License-Identifier: GPL-3.0-or-later
    # Copyright (c) vertbyqb 2021
    # You can use this in your plugin. Just change the files and strings arrays and you're good to go.

    files = ["help/url.md"]
    strings = ["""
**pandoc**

Convert publication using pandoc.

Usage: `pandoc <output format> <output file>`.
"""]

    for n, file in enumerate(files):
        if args[0] == file:
            args[1] = args[1] + strings[n]

    return args


# This is the data that the plugin module reads.
plugin_data = {
    "title":"Pandoc",
    "author":"vertbyqb",
    "license":"GPL-3.0-or-later",
    "description": "Convert publications using Pandoc",
    "flbry":"terminal",
    "functions":[
        {
            "command": "pandoc",
            "flbry.url.get": pandoc_convert
        },
        {
            "command": False,
            "flbry.markdown.draw": inject_help
        }
    ]}
